package cn.zk.question.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class TcpClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private int count;
    /**
     * 读取数据
     * @param ctx
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        byte[] buffer = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(buffer);
        // buffer转为字符串
        String message = new String(buffer, StandardCharsets.UTF_8);
        System.out.println("==>客户端收到数据:"+message);
        System.out.println("==>客户端收到的消息量:"+(++this.count));
    }

    /**
     * 通道活跃
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 连续10发送,会发现客户端并不是接收10次,而是少于10次，出现TCP沾包、拆包问题。
        for (int i=0;i<10;i++) {
            String message = "hello,server"+i;
            ByteBuf send = Unpooled.copiedBuffer(message, StandardCharsets.UTF_8);
            ctx.writeAndFlush(send);
        }
    }

    /**
     * 通道不活跃
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    /**
     * 捕获的异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        // 关闭通道
        ctx.close();
    }

}
